package com.qbw.app.module.vehicle.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.View;

import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.http.okhttp.HttpTask;
import com.lib.util.ScreenUtil;
import com.qbw.actionmanager.ActionManager;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.XApplication;
import com.qbw.app.databinding.VehicleActivityTravelListBinding;
import com.qbw.app.manager.UnitManager;
import com.qbw.app.model.TravelChart;
import com.qbw.app.model.TravelData;
import com.qbw.app.model.Vehicle;
import com.qbw.app.module.common.fragment.CommonFragment;
import com.qbw.app.module.common.fragment.DateSelectDialogFragment;
import com.qbw.app.module.common.util.PositionUtil;
import com.qbw.app.module.home.holder.HomeTravelHolder;
import com.qbw.app.module.vehicle.adapter.VehicleAdapter;
import com.qbw.app.module.vehicle.adapter.VehicleViewType;
import com.qbw.app.module.vehicle.popwindow.VehicleSelectPopWindow;
import com.qbw.app.request.impl.UserRequest;
import com.qbw.app.utils.BigDecimalUtil;
import com.qbw.app.utils.MyBarMarkerView;
import com.qbw.core.holder.EmptyHolder;
import com.qbw.core.model.Empty;
import com.qbw.core.util.DateUtil;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static com.qbw.app.Constant.KEY_VEHICLE;
import static com.qbw.app.module.vehicle.adapter.VehicleViewType.VT_TRAVEL_ITEM;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_TRAVEL_LIST;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_TRAVEL_TRAVELCHART;
import static com.qbw.app.request.impl.VehicleRequest.METHOD_VEHICLE_LIST;

/**
 * @author QBW
 * @date 2019/8/27
 */
public class VehicleTravelListFragment extends CommonFragment<VehicleActivityTravelListBinding> implements ActionManager.Listener,HomeTravelHolder.Listener, DateSelectDialogFragment.Listener {

    private long startTime,endTime;
    private Vehicle mVehicle;
    private int mPageNo = 1;
    private VehicleAdapter mAdapter;
    private Vehicle.Response responseVehicle;
    private String tempYear,tempMonth;
    private List<Integer> mSortedHeaderViewTypes = new ArrayList<>();
    public static VehicleTravelListFragment createInstance() {
        VehicleTravelListFragment ins = new VehicleTravelListFragment();
        return ins;
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.vehicle_activity_travel_list;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mSortedHeaderViewTypes.add(VehicleViewType.VT_TRAVEL_CHART);
//        mSortedHeaderViewTypes.add(VehicleViewType.VT_TRAVEL_ITEM);
        mBinding.rcv.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.rcv.setItemAnimator(null);
        mBinding.rcv.addItemDecoration(new InnerDecoration());
        mAdapter = new VehicleAdapter(getContext(), this);
        mBinding.rcv.setAdapter(mAdapter);
        mBinding.llCurrentVehicle.setOnClickListener(this);
        mBinding.rlDate.setOnClickListener(this);
        mBinding.rlAddDate.setOnClickListener(this);
        mBinding.rlReduceDate.setOnClickListener(this);
        mActionManager.addInterestedAction(this, VehicleSelectPopWindow.SelectedVehicleChangedAction.class);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        //获取当前月最后一天
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastDay = sdf.format(calendar.getTime());
        int month = calendar.get(Calendar.MONTH)+1;
        tempMonth = calendar.get(Calendar.MONTH)+1+"";
        tempYear = calendar.get(Calendar.YEAR)+"";
        mBinding.tvDate.setText(calendar.get(Calendar.YEAR)+" 年 "+month+" 月");
        mBinding.tvDistanceTime.setText(calendar.get(Calendar.YEAR)+" 年 "+month+" 月");
        startTime = DateUtil.getStringToDate(tempYear+"-"+tempMonth+"-"+"01"+" 00:00:00","yyyy-MM-dd HH:mm:ss");
        endTime = DateUtil.getStringToDate(lastDay+" 23:59:59","yyyy-MM-dd HH:mm:ss");

        mBinding.refreshLayout.setEnableLoadMore(true);
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPageNo++;
                if(mVehicle != null){
                    getTravleList();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (refreshLayout != null) {
                    mPageNo = 1;
                    if(mVehicle != null){
                        getTravleList();
                        refreshLayout.setEnableRefresh(true);
                    }else{
                        finishRefresh();
                    }

                }
            }
        });
        getVehicleList();
    }

    @Override
    public void onResume() {
        super.onResume();
        if(mVehicle != null){
            getTravleList();
        }
    }

    private void setBarChartView(TravelChart.ResponseList respeList) {
        float max= 0;
        for(int i = 0;i<respeList.getData().getList().size();i++){
                if(max < respeList.getData().getList().get(i).getSumMile()){
                    max = respeList.getData().getList().get(i).getSumMile();
                }
        }

        mBinding.chart.getDescription().setEnabled(false);
        mBinding.chart.setDrawGridBackground(false);

        XAxis xAxis =  mBinding.chart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                if(value == 0){
                    return tempMonth+" - 1";
                }else if(value == 5){
                    return tempMonth+" - 6";
                }else if(value == 10){
                    return tempMonth+" - 11";
                }else if(value == 15){
                    return tempMonth+" - 16";
                }else if(value == 20){
                    return tempMonth+" - 21";
                }else if(value == 25){
                    return tempMonth+" - 26";
                }else if(value == 30){
                    return "";
                }
                return "";
            }
        });
        YAxis leftAxis = mBinding.chart.getAxisLeft();
        leftAxis.setLabelCount(5, false);
        leftAxis.setSpaceTop(15f);
        if(max == 0.0){
            leftAxis.setAxisMaximum(150f);  // 设置y轴的最大值
        }else{
            if(max<100){
                leftAxis.setAxisMaximum(50f);  // 设置y轴的最大值
            }else{
                leftAxis.setAxisMaximum(max+10);  // 设置y轴的最大值
            }
        }
        leftAxis.setAxisMinimum(0f);  // 设置y轴的最小值
        leftAxis.setDrawAxisLine(false);
        YAxis rightAxis =mBinding.chart.getAxisRight();
        rightAxis.setLabelCount(5, false);
        rightAxis.setSpaceTop(15f);
        if(max == 0.0){
            rightAxis.setAxisMaximum(150f);  // 设置y轴的最大值
        }else{
            if(max<100){
                rightAxis.setAxisMaximum(50f);  // 设置y轴的最大值
            }else{
                rightAxis.setAxisMaximum(max+10);  // 设置y轴的最大值
            }

        }
        rightAxis.setAxisMinimum(0f);  // 设置y轴的最小值
        rightAxis.setDrawAxisLine(false);
        rightAxis.setDrawLabels(false);
        mBinding.chart.setTouchEnabled(true); // 设置是否可以触摸
        mBinding.chart.setDragEnabled(true);// 是否可以拖拽
        mBinding.chart.setDoubleTapToZoomEnabled(false);//设置双击不放大
        mBinding.chart.setData(generateData(1,respeList));
        mBinding.chart.setFitBars(true);
        mBinding.chart.animateY(700);
        Legend mLegend = mBinding.chart.getLegend(); // 设置比例图标示，就是那个一组y的value的
        mLegend.setEnabled(false);//true和false能控制比例图标识是否显示

        MyBarMarkerView mv = new MyBarMarkerView(getContext(), R.layout.custom_part_shadow_popup);
        mv.setOnClickMarker(new MyBarMarkerView.OnClickMarker() {
            @Override
            public void onMarkerInfo(TravelChart travelChart) {
                if(travelChart.getSumMile() !=0.0){
                    String time =  DateUtil.getDateToString(travelChart.getTime(),"MM月dd日");
                    mBinding.tvTravelMarker.setVisibility(View.VISIBLE);
                    mBinding.tvTravelMarker.setText(time+BigDecimalUtil.round(travelChart.getSumMile(),1)+"km");
                    if (UnitManager.getInstance().isUseKm()) {
                    }else{
                        String mi = String.format(Locale.getDefault(),
                                "%.1fmi",
                                PositionUtil.convertKmToMile(travelChart.getSumMile()));
                        mBinding.tvTravelMarker.setText(time+mi);
                    }
                }else{
                    mBinding.tvTravelMarker.setVisibility(View.GONE);
                }

            }
        });
        mBinding.chart.setMarkerView(mv);

    }

    private BarData generateData(int cnt,TravelChart.ResponseList respeList) {
        List<TravelChart> travelCharts = respeList.getData().getList();

        if(respeList.getData().getList().size() <=30){
            TravelChart travelChart = new TravelChart();
            travelChart.setSumMile(0);
            travelCharts.add(travelChart);
        }
        ArrayList<BarEntry> entries = new ArrayList<>();
        for (int i = 0; i < travelCharts.size(); i++) {
            entries.add(new BarEntry(i, travelCharts.get(i).getSumMile(),travelCharts.get(i)));

        }
        BarDataSet d = new BarDataSet(entries, "");
        d.setColors(ColorTemplate.TRIP_VORDIPLOM_COLORS);
        d.setBarShadowColor(Color.rgb(144, 152, 164));
        d.setDrawValues(false);
        ArrayList<IBarDataSet> sets = new ArrayList<>();
        sets.add(d);

        BarData cd = new BarData(sets);
        cd.setBarWidth(0.9f);
        return cd;
    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == R.id.ll_current_vehicle) {
            if(responseVehicle != null){
                VehicleSelectPopWindow window = new VehicleSelectPopWindow(getContext(),
                        responseVehicle.getData());
                window.showAsDropDown(v,
                        ScreenUtil.dp2px(getContext(), 13),
                        ScreenUtil.dp2px(getContext(), 10));
            }
        }else if(vid == R.id.rl_date){
            DateSelectDialogFragment.createInstance()
                    .show(getChildFragmentManager(), "travel-select");
        } else if(vid == R.id.rl_reduce_date){
            mBinding.tvTravelMarker.setVisibility(View.GONE);
            updateDate(tempYear+"-"+tempMonth,false);
        }else if(vid == R.id.rl_add_date){
            updateDate(tempYear+"-"+tempMonth,true);
            mBinding.tvTravelMarker.setVisibility(View.GONE);
        }
    }



    private void getTravleList(){
        mGeneralManager.getRequestManager()
                .getVehicleRequest()
                .getTravelList(mVehicle.getVehicleCode(),
                        startTime,
                        endTime,
                        mPageNo,
                        Constant.PAGESIZE_10,
                        this)
                .execute();

    }

    private void getTravleChart(){
        mGeneralManager.getRequestManager()
                .getVehicleRequest()
                .getTravellChart(mVehicle.getVehicleCode(),
                        startTime,
                        endTime,
                        this)
                .execute();
    }

    private void getVehicleList() {
        mGeneralManager.getRequestManager().getVehicleRequest().getVehicleList(this).execute();
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_TRAVEL_LIST)) {
            TravelData.Response travelData = (TravelData.Response) entity;
//            Travel.ResponseList responseList = travelData.getData().getTravelList();
            int page = (int) httpTask.getParams().get("page");
            boolean refresh = page == 1;
            mAdapter.clear();
//            if (!responseList.getData().isEmpty()) {
////                for (Travel travel : responseList.getData().getList()) {
////                    travel.setVehicle(mVehicle);
////                }
////            }

            mAdapter.addChild(travelData.getData().getTravelList());
            boolean noMore = travelData.getData().getTravelList().size() < Constant.PAGESIZE_10;
            if (noMore) {
                mBinding.refreshLayout.setEnableLoadMore(false);
            }
            if (mAdapter.getChildCount() <= 0) {
                mAdapter.showEmpty(new Empty(0, EmptyHolder.ModelId.M_VEHICLE_NO_TRAVEL));
            }
            if (UnitManager.getInstance().isUseKm()) {
                mBinding.tvTotalDistance.setText(BigDecimalUtil.round(travelData.getData().getTravelStatistic().getSumMile(),1)+"km");
            }else{
                String mi = String.format(Locale.getDefault(),
                        "%.1fmi",
                        PositionUtil.convertKmToMile(Double.parseDouble(travelData.getData().getTravelStatistic().getSumMile())));
                mBinding.tvTotalDistance.setText(mi);
            }
            finishRefresh();
            getTravleChart();
        }else   if (METHOD_VEHICLE_LIST.equals(method)) {
            responseVehicle= (Vehicle.Response) entity;
            mVehicle = responseVehicle.getData().getIndexVehicle();
            if(mVehicle != null){
                mBinding.setVehicle(responseVehicle.getData().getIndexVehicle());
                mPageNo = 1;
                getTravleList();
            }
        }else if (method.equals(UserRequest.METHOD_UPDATE_INFO)) {
            getVehicleList();
            closeLoadingDialog();
        }else if (method.equals(METHOD_TRAVEL_TRAVELCHART)) {
            TravelChart.ResponseList responseList = (TravelChart.ResponseList) entity;
            setBarChartView(responseList);
        }

    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(METHOD_TRAVEL_LIST)) {
            int page = (int) httpTask.getParams().get("page");
            boolean refresh = page == 1;
            finishRefresh();
        }
    }

    public void finishRefresh() {
        if (mBinding.refreshLayout != null) {
            mBinding.refreshLayout.finishRefresh();
            mBinding.refreshLayout.finishLoadMore();
        }
    }


    @Override
    public int onGetWhereHomeTravelHolderIn() {
        return HomeTravelHolder.IN_TRAVEL_LIST;
    }

    @Override
    public void onStrokeDateSelect(int year, int month) {
//        startTime = DateTimeUtil.getTimestampByYearMonth(year, month);
        mBinding.tvDate.setText(year+" 年 "+month+" 月");
        mBinding.tvDistanceTime.setText(year+" 年 "+month+" 月");
        mBinding.tvTravelMarker.setVisibility(View.GONE);
        String formatDate = year+"-"+month;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        Date now = null;
        try {
            now = df.parse(formatDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前月最后一天
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastDay = sdf.format(calendar.getTime());
        startTime = DateUtil.getStringToDate(year+"-"+month+"-"+"01"+" 00:00:00","yyyy-MM-dd HH:mm:ss");
        endTime = DateUtil.getStringToDate(lastDay+" 23:59:59","yyyy-MM-dd HH:mm:ss");

        getTravleList();
    }


    private void updateDate(String passTime,boolean isAdd){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
        SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
        Date now = null;
        try {
            now = df.parse(passTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        if(isAdd){
            calendar.add(Calendar.MONTH, 1);
        }else{
            calendar.add(Calendar.MONTH, -1);
        }

        Date date = calendar.getTime();
        String year = yearFormat.format(date);
        String month = monthFormat.format(date);
        mBinding.tvDate.setText(year+" 年 "+month+" 月");
        mBinding.tvDistanceTime.setText(year+" 年 "+month+" 月");
        tempMonth = month;
        tempYear = year;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前月最后一天
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastDay = sdf.format(calendar.getTime());
        startTime = DateUtil.getStringToDate(tempYear+"-"+tempMonth+"-"+"01"+" 00:00:00","yyyy-MM-dd HH:mm:ss");
        endTime = DateUtil.getStringToDate(lastDay+" 23:59:59","yyyy-MM-dd HH:mm:ss");

        getTravleList();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ActionManager.getInstance().removeInterestedActions(this);

    }

    @Override
    public void onActionTriggered(Object action) {

        if (action instanceof VehicleSelectPopWindow.SelectedVehicleChangedAction) {
            VehicleSelectPopWindow.SelectedVehicleChangedAction vehicleChangedAction = (VehicleSelectPopWindow.SelectedVehicleChangedAction) action;
            Vehicle vehicle = vehicleChangedAction.getAction();
            showLoadingDialog("");
            mGeneralManager.getRequestManager()
                    .getUserRequest()
                    .updateInfo(null, vehicle.getVehicleCode(), null, null, this)
                    .addExtraParam(KEY_VEHICLE, vehicle)
                    .execute();
        }
    }

    private static class InnerDecoration extends RecyclerView.ItemDecoration {
        private int mSpace14;
        private int mSpace11;

        public InnerDecoration() {
            Context context = XApplication.getInstance();
            mSpace11 = ScreenUtil.dp2px(context, 11);
            mSpace14 = ScreenUtil.dp2px(context, 14);
        }

        @Override
        public void getItemOffsets(@NonNull Rect outRect,
                                   @NonNull View view,
                                   @NonNull RecyclerView parent,
                                   @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            int ap = parent.getChildAdapterPosition(view);
            if (ap == RecyclerView.NO_POSITION) {
                return;
            }
            int vt = parent.getAdapter().getItemViewType(ap);
            switch (vt) {
                case VT_TRAVEL_ITEM:
                    outRect.left = mSpace14;
                    outRect.right = mSpace14;
                    outRect.top = mSpace11;
                    break;
                default:
                    break;
            }
        }
    }
}
